package com.wzdigit.wms.raw.service.asn;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.framework.Shift;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.asn.AsnDtlGoods;
import com.wzdigit.wms.basic.domain.asn.AsnHeader;
import com.wzdigit.wms.basic.enums.AsnHeaderStatusEnum;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlGoodsMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnHeaderMapper;
import com.wzdigit.wms.raw.client.response.asn.AsnResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AsnCancleService {

    @Autowired
    AsnHeaderMapper asnHeaderMapper ;

    @Autowired
    AsnDtlMapper asnDtlMapper;

    @Autowired
    AsnDtlGoodsMapper asnDtlGoodsMapper ;


    /**
        * @as
        * @return com.wzdigit.wms.basic.client.response.Result<?>
        * @author shuaic
        * @date 2021/8/13 19:25
     *
    */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public AsnResponse cancelAsnNo(String  asnNo) {
        log.info("调用SRM删除单据接口==》"+asnNo);
        try {
            AsnHeader asnHeader = asnHeaderMapper.selectOne(new QueryWrapper<AsnHeader>(new AsnHeader().setAsnNo(asnNo)));
            if(asnHeader==null){
                return  new AsnResponse(asnNo,"F","未查到该单据号！");
            }
            //查询是否有goods
            List<AsnDtlGoods> goodsList = asnDtlGoodsMapper.selectAsnDtlGoodsByAsnNo(asnHeader.getAsnNo());

            if(asnHeader.getStatus().equals(AsnHeaderStatusEnum.CREATE.code) || asnHeader.getStatus().equals(AsnHeaderStatusEnum.CANCEL.code)){
                if(goodsList!=null&&goodsList.size()>0){
                    return  new AsnResponse(asnNo,"F","订单已经有预收条码,请联系对应仓管员");
                }
                asnDtlMapper.delete(new QueryWrapper<>(new AsnDtl().setAsnHeaderId(asnHeader.getAsnHeaderId())));
                asnHeaderMapper.deleteById(asnHeader.getAsnHeaderId());
                return  new AsnResponse(asnNo,"S","取消成功");
            }else {
                return  new AsnResponse(asnNo,"F","单据状态不为新建或者取消，无法取消！");
            }
        }catch (Exception e){
            e.printStackTrace();
            Shift.fatal("服务端异常");
            return new AsnResponse(asnNo,"F","服务端异常");
        }
    }


}

